﻿using System;
using System.Linq;
using YBApproval.Common;
using YBApproval.IDAL;
using YBApproval.BLL;
using YBApproval.Model;
using System.Collections.Generic;
using System.Web;

namespace YBApproval
{
    /// <summary>
    /// 
    /// </summary>
    public partial class Logout : System.Web.UI.Page
    {

        #region Protected Method
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Session.Abandon();
            }            
        }

        /// <summary>
        /// Handles the Click event of the btnLogin control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (!ValidateUserName())
            {
                return;
            }
            UserProfile inUser = new UserProfile
            {
                LoginName = txtUsername.Text, //GetUserName();
                Pwd = Encrypt.EncryptDES(txtPassword.Text, Encrypt.DefaultEncryptKey)
            };


            //string domainName = GetDomainName(txtUsername.Text);

            try
            {
                UserProfile cUser;
                using (IUserProfile _userProfileDAL = DALFactory.GetDAL<IUserProfile>())
                {
                    cUser = _userProfileDAL.UserLogin(inUser);
                }         

                if (cUser != null)
                {
                    YBPSession.Instance.CurrentUser = cUser;
                    using (IUserProfile _userProfileDAL = DALFactory.GetDAL<IUserProfile>())
                    {
                        if (cUser.Delegate.HasValue)
                        {
                            YBPSession.Instance.CurUserDelegate = _userProfileDAL.GetUserByID(cUser.Delegate.Value);
                        }
                    }
                    using (IRole _RoleDAL = DALFactory.GetDAL<IRole>())
                    {
                        if (!string.IsNullOrEmpty(cUser.RoleId))
                        {
                            var strIds = cUser.RoleId.Split(',').ToList<string>();
                            List<int> Ids = new List<int>();
                            foreach (var item in strIds)
                            {
                                Ids.Add(int.Parse(item));
                            }
                            YBPSession.Instance.MyRoleList = _RoleDAL.GetUserRoleList(Ids);
                        }
                        YBPSession.Instance.AllRolesList = _RoleDAL.GetAll();
                    }

                    Uri Url = Page.Request.Url;
                    Url = Page.Request.UrlReferrer;
                    
                    Url = Page.Request.UrlReferrer;
                    string urlstr = System.IO.Path.GetFileName(Request.FilePath.ToString());
                    if(Url !=null)
                        Response.Redirect(Url.OriginalString);
                    else
                        Response.Redirect(@"~/Default.aspx");
                }
                else
                {
                    errorLabel.Text = "登陆失败，请检查用户名密码是否正确！";
                }
            }
            catch (Exception ex)
            {
                errorLabel.Text = ex.Message;
            }
        } 
        #endregion

        #region Private Method
        /// <summary>
        /// Gets the name of the user.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        private string GetUserName(string userName)
        {
            return userName.Split(new[] { '\\' })[1];
        }

        /// <summary>
        /// Gets the name of the domain.
        /// </summary>
        /// <param name="userName">Name of the domain.</param>
        /// <returns></returns>
        private string GetDomainName(string userName)
        {
            return userName.Split(new[] { '\\' })[0];
        }

        /// <summary>
        /// Validates the name of the user.
        /// </summary>
        /// <returns></returns>
        private bool ValidateUserName()
        {
            string userName = txtUsername.Text;

            //if (!userName.Contains(@"\"))
            //{
            //    errorLabel.Visible = true;
            //    errorLabel.Text = @"Please add the domain before the username,like domain\userName";
            //    return false;
            //}
            return true;    
        }
        #endregion
    }
}
